package org.jaaksi.customviewdemo.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import extension.dp
import java.util.*

class TimerView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)

    private var degrees = 0f
    private var radius = 100.dp.toFloat()
    private var indicatorLength = 40.dp.toFloat()
    private var rulerLength = 10.dp.toFloat()
    private var timer = Timer()
    private var task = object : TimerTask() {
        override fun run() {
            invalidate()
        }
    }

    init {
        paint.apply {
            style = Paint.Style.STROKE
            // 指定画笔的开始结束描边处理
            strokeCap = Paint.Cap.ROUND
            // 指定画笔的连接处的描边处理
//            strokeJoin = Paint.Join.MITER;
            color = Color.BLUE
            isAntiAlias = true
            strokeWidth = 5.dp.toFloat()
        }
        timer.schedule(task, 1000, 1000)

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawCircle(width / 2f, height / 2f, radius, paint)
        // Canvas.save()保存的是绘图坐标系
        canvas.save()
        var degrees = 0f
        while (degrees != 360f) {
            canvas.drawLine(
                width / 2f,
                height / 2f - radius,
                width / 2f,
                height / 2f - radius + rulerLength,
                paint
            )
            degrees += 15f
            canvas.rotate(15f, width / 2f, height / 2f)
        }
        // 恢复到旋转前的状态
        canvas.restore()
        canvas.rotate(this.degrees, width / 2f, height / 2f)
        this.degrees += 6f
        canvas.drawLine(
            width / 2f,
            height / 2f,
            width / 2f,
            height / 2f - indicatorLength, paint
        )
    }

    fun destroy(){
        timer.cancel()
    }
}